package com.gome.ss.webserver.servlet.api;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.gome.ss.common.AppConfiguer;
import com.gome.ss.common.Utils;
import com.gome.ss.core.plugin.Plugin;
import com.gome.ss.core.plugin.PluginManager;

public class UploadPluginServlet extends HttpServlet {
	private static Logger logger = Logger.getLogger(UploadPluginServlet.class);
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
	    // TODO Auto-generated method stub
    	resp.setContentType("text/plain;charset=gbk");
    	
    	UploadStatus status = new UploadStatus(); //上传状态
    	UploadListener listener = new UploadListener(status); //监听器
    	req.getSession(true).setAttribute("uploadStatus", status); //把状态放到Session里
    	
        PrintWriter pw = resp.getWriter();
        try {
            DiskFileItemFactory diskFactory = new DiskFileItemFactory();  
            // 硬盘缓存 1M  
            diskFactory.setSizeThreshold(4 * 1024);  
            // 临时文件目录  
            diskFactory.setRepository(new File("/tmp"));
            
            ServletFileUpload upload = new ServletFileUpload(diskFactory);  
            // 设置允许上传的最大文件大小 50M
            upload.setSizeMax(50 * 1024 * 1024);
            // 设置上传listener 
            upload.setProgressListener(listener);
            // 解析HTTP请求消息头  
            List fileItems = upload.parseRequest(req);  
            Iterator iter = fileItems.iterator();  
            
            while(iter.hasNext())  
            {  
                FileItem item = (FileItem)iter.next();  
                if(item.isFormField())
                {  
                    processFormField(item, pw);  
                }else{  
                    processUploadFile(item, pw);  
                }  
            }
            pw.print("1");
            pw.close();
        } catch (Exception e) {
        	logger.error(Utils.getTrace(e));
        }
    }
    
    // 处理表单内容  
    private void processFormField(FileItem item, PrintWriter pw)  
        throws Exception {  
        String name = item.getFieldName();  
        String value = item.getString();
    }  
    
    // 处理上传的文件  
    private void processUploadFile(FileItem item, PrintWriter pw)  
        throws Exception {
        String filename = item.getName();         
        logger.info("Plugin file name ：" + filename);
        
        int index = filename.lastIndexOf("\\");
        filename = filename.substring(index + 1, filename.length());  
 
        long fileSize = item.getSize();  
 
        if("".equals(filename) && fileSize == 0)  
        {             
        	logger.info("Plugin file is null ...");  
            return;  
        }
        
        File uploadFile = new File(AppConfiguer.getPluginDir() + "/" + filename);  
        item.write(uploadFile);  
        logger.info("File size ：" + fileSize);  
        
        String pluginName = PluginManager.getInstance().getPluginName(filename);
        if (pluginName != null && !pluginName.isEmpty()) {
        	List<Plugin> plugins = PluginManager.getInstance().getPlugin(pluginName);
        	for (Plugin plugin : plugins) {
        		if (plugin.getHandle().processable()) {
        			plugin.getTaskProcess().close();
        		}
        	}
        }
        
        PluginManager.getInstance().loadPluginFromJar(filename, true);
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
	    // TODO Auto-generated method stub
    	resp.setHeader("Cache-Control", "no-store");
    	resp.setHeader("Pragrma", "no-cache");
    	resp.setDateHeader("Expires", 0);
    	resp.setCharacterEncoding("UTF-8");

    	UploadStatus status = (UploadStatus) req.getSession(true)
    	.getAttribute("uploadStatus");
    	if (status == null) {
    		resp.getWriter().println("-1"); return;
    	}
    	
    	long startTime = status.getStartTime();

    	int percent = (int)(100 * (double)status.getBytesRead() / (double)
    	status.getContentLength());
    	double length = ((double)status.getBytesRead())/1024/1024;
    	double totalLength = ((double)status.getContentLength())/1024/1024;

    	//格式化：百分比||已完成数（M）||文件总长度（M）|| 正在上传第几个文件 || 开始时间
    	String value = percent + "||"+ length+"||"+totalLength +"||"+status.getItems() + "||" + startTime;
    	resp.getWriter().println(value);
    }

}
